package com.guaoran.source.mybatis.v2.result;

import com.guaoran.source.mybatis.v2.config.Configuration;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : 孤傲然
 * @Description :
 * @date :2018/5/26 12:56
 */
public class ResultSetHandler {
    private Configuration configuration;
    public <T> List<T> handle(ResultSet resultSet, Class type) throws SQLException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Object resultObj = null;
        List<Object> resultObjList = new ArrayList<Object>();
        //TODO 封装结果可以从映射的文件中取 configuration
        while(resultSet.next()){
            resultObj = new DefaultObjectFactory().create(type);
            for (Field field : resultObj.getClass().getDeclaredFields()) {
                setValue(resultObj, field, resultSet);
            }
            resultObjList.add(resultObj);
        }
        return (List<T>) resultObjList;
    }

    private void setValue(Object resultObj, Field field, ResultSet rs) throws NoSuchMethodException, SQLException, InvocationTargetException, IllegalAccessException {
        Method setMethod = resultObj.getClass().getMethod("set" + upperCapital(field.getName()), field.getType());
        setMethod.invoke(resultObj, getResult(field,rs));
    }
    private Object getResult(Field field, ResultSet rs) throws SQLException {
        //TODO type handles
        //bean属性的名字必须要和数据库column的名字一样
        Class<?> type = field.getType();
        if(Integer.class == type){
            return rs.getInt(field.getName());
        }
        if(int.class == type){
            return rs.getInt(field.getName());
        }
        if(String.class == type){
            return rs.getString(field.getName());
        }
        return rs.getString(field.getName());
    }

    private String upperCapital(String name) {
        String first = name.substring(0, 1);
        String tail = name.substring(1);
        return first.toUpperCase() + tail;
    }
}
